package com.myres.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.myres.model.Product;
import com.myres.model.Shop;
import com.myres.model.User;

public class ShopDao extends HibernateDaoSupport {

	public long insertShop(Shop shop) {
		HibernateTemplate ht=getHibernateTemplate();
		ht.setFlushMode(HibernateTemplate.FLUSH_EAGER);
		ht.save(shop);
		return shop.getId();
	}

	public long insertUser(User user) {
		HibernateTemplate ht=getHibernateTemplate();
		ht.setFlushMode(HibernateTemplate.FLUSH_EAGER);  
		ht.save(user);
		return user.getId();
	}

	@SuppressWarnings("unchecked")
	public List<Shop> findAll() {
		List<Shop> shopList;
		String hql = "FROM Shop";

		shopList = (List<Shop>) getHibernateTemplate().find(hql);
		System.out.println("shop size=" + shopList.size());
		return shopList;
	}

	public Shop get(int id) {
		return getHibernateTemplate().get(Shop.class, id);
	}

	public int save(Shop shop) {
		getHibernateTemplate().save(shop);
		return shop.getId();
	}

	public void delete(Shop shop) {
		getHibernateTemplate().delete(shop);
	}

	public void delete(int id) {
		delete(get(id));
	}

	private List<Shop> getInRangeWithHql(final Integer startWith,
			final Integer size, final String hql) {
		List<Shop> resultList = getHibernateTemplate().executeFind(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						List<Shop> result = session.createQuery(hql)
								.setFirstResult(startWith).setMaxResults(size)
								.list();
						return result;
					}

				});
		return resultList;
	}

	/**
	 * 
	 * @param status
	 * @param startWith
	 *            keep null if you don't want to use in range function.
	 * @param size
	 *            same as this one.
	 * @return
	 */
	public List<Shop> findByStatusInRange(int status, Integer startWith,
			Integer size) {
		String hql = "from Shop s where status='" + status + "'";
		if (startWith == null || size == null) {
			return (List<Shop>) getHibernateTemplate().find(hql);
		} else {
			return getInRangeWithHql(startWith, size, hql);
		}
	}
}
